package itsense.client;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;


import itsense.model.ClientDTO;

import com.smartgwt.client.widgets.events.ClickEvent;  
import com.smartgwt.client.widgets.events.ClickHandler; 

import com.smartgwt.client.widgets.events.CloseClickHandler;  
import com.smartgwt.client.widgets.events.CloseClientEvent;  
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.DateDisplayFormat;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.Side;
import com.smartgwt.client.types.TitleOrientation;

import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.CheckboxItem;
import com.smartgwt.client.widgets.form.fields.ComboBoxItem;
import com.smartgwt.client.widgets.form.fields.DateItem;
import com.smartgwt.client.widgets.form.fields.SectionItem;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.StaticTextItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Img;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HStack;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.layout.VStack;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;


public class ClientListPanel extends Window {
	ListGrid clientGrid = new ListGrid();
	IButton addButton = new IButton("Add");
	public static ClientListPanel instance;
	
	public ClientListPanel() {
		instance = this;
		init();
	}
	
	private void init(){
		
		setTitle("Clients");
		setWidth(900);
		setHeight(500);
		setCanDragResize(true);
		setCanDragReposition(true);
		
		clientGrid.setWidth100();  
		clientGrid.setHeight100();  
		clientGrid.setShowAllRecords(true);  
		clientGrid.setShowEmptyMessage(true);
		clientGrid.setEmptyMessage("<br>There are no clients yet in the database");
		
		
		ListGridField id = new ListGridField("id","Id");;
		ListGridField email = new ListGridField("email","E-mail");
		ListGridField firstName = new ListGridField("firstName","First name");
		ListGridField lastName = new ListGridField("lastName","Last name");
		ListGridField birthDate = new ListGridField("birthDate","Birth date");
		birthDate.setType(ListGridFieldType.DATE);
		birthDate.setDateFormatter(DateDisplayFormat.TOEUROPEANSHORTDATE);
		ListGridField anniversary = new ListGridField("anniversary","Anniversary");
		anniversary.setType(ListGridFieldType.DATE);
		anniversary.setDateFormatter(DateDisplayFormat.TOEUROPEANSHORTDATE);

		ListGridField mobilePhone = new ListGridField("mobilePhone","Mobile phone");
		ListGridField workPhone = new ListGridField("workPhone","Work phone");
		ListGridField homePhone = new ListGridField("homePhone","Home phone");
		ListGridField gender = new ListGridField("gender","Gender");
		ListGridField title = new ListGridField("title","Title");
		ListGridField occupation = new ListGridField("occupation","Occupation");

		
		ListGridField address = new ListGridField("address","Address");
		clientGrid.setCellHeight(60);
		clientGrid.setWrapCells(true);
		clientGrid.setFields(id, firstName , lastName, mobilePhone,workPhone,homePhone,  address, email, gender, title,occupation, birthDate, anniversary);
    	getMembersFromServer();
		
		addButton.setIcon("User-Administrator-Red-icon.png");  
		addButton.setIconOrientation("right");  
		addButton.setWidth(100);

	
		VLayout vLayout = new VLayout();
		vLayout.setWidth100();
		vLayout.setHeight100();
		vLayout.setMembersMargin(10);
		HStack hStack = new HStack();
		hStack.setMembersMargin(10);
		
		hStack.setHeight(30);
		hStack.addMember(addButton);
		
		vLayout.addMember(clientGrid);
		vLayout.addMember(hStack);
		addItem(vLayout);
		
		addCloseClickHandler(new CloseClickHandler() {
			public void onCloseClick(CloseClientEvent event) {
				BeautySenseGWT.clientListPanel.hide();
				BeautySenseGWT.clientListPanel.destroy();
				BeautySenseGWT.clientListPanel = null;
				BeautySenseGWT.clientMenuItem.setEnabled(true);
				
			}
		});

		addButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				new AddClientWindow();
			}
		});
		
	}

	
	public void getMembersFromServer(){
	
	BeautySenseGWT.service.getClients(new AsyncCallback<List<ClientDTO>>() {
		public void onSuccess(List<ClientDTO> result) {
			ListGridRecord[] clientList = new ListGridRecord[result.size()];
			for (int i = 0 ; i < result.size() ;i++){
				clientList[i] = new ListGridRecord();


				
				
				clientList[i].setAttribute("id", result.get(i).getId());
				clientList[i].setAttribute("email", result.get(i).getEmail());
				clientList[i].setAttribute("firstName", result.get(i).getFirstName());
				clientList[i].setAttribute("lastName", result.get(i).getLastName());
				clientList[i].setAttribute("birthDate", result.get(i).getBirthDate());
				clientList[i].setAttribute("anniversary", result.get(i).getAnnivarsery());

				clientList[i].setAttribute("mobilePhone", result.get(i).getMobilePhone());
				clientList[i].setAttribute("workPhone", result.get(i).getWorkPhone());
				clientList[i].setAttribute("homePhone", result.get(i).getHomePhone());
				String addressText = result.get(i).getAddressLine1() +" <br/>" + result.get(i).getAddressLine2()+" <br/>" + result.get(i).getPostCode() + " " + result.get(i).getCity() + " <br/>" + result.get(i).getCountry();
				clientList[i].setAttribute("address",addressText);
/*				clientList[i].setAttribute("country", result.get(i).getCountry());
				clientList[i].setAttribute("city", result.get(i).getCity());
				clientList[i].setAttribute("addressLine1", result.get(i).getAddressLine1());
				clientList[i].setAttribute("addressLine2", result.get(i).getAddressLine2());
				clientList[i].setAttribute("postCode", result.get(i).getPostCode());
*/
			}
			clientGrid.setData(clientList);
		}
		
		public void onFailure(Throwable caught) {
		}
	});
} 

}
//--------------------------------------------------------------------------------------------------------------------------

class AddClientWindow extends Window{
	
	public static AddClientWindow instance;
	IButton cancelButton = new IButton("Cancel");
	IButton addButton = new IButton("Add");
	DynamicForm generalForm = new DynamicForm();  
	DynamicForm phoneForm = new DynamicForm();  
	DynamicForm addressForm = new DynamicForm();  
	DynamicForm miscellaneousForm = new DynamicForm();  
	DynamicForm referenseForm = new DynamicForm();  
	DynamicForm mailingForm = new DynamicForm();  
	TextItem firstNameItem = new TextItem("firstName","First name");  
	TextItem lastNameItem = new TextItem("lastName","Last name");  
	StaticTextItem idItem = new StaticTextItem("id","Id");  

	TextItem homePhoneItem = new TextItem("homePhone","Home");  
	TextItem mobilePhoneItem = new TextItem("mobilePhone","Mobile");  
	TextItem workPhoneItem = new TextItem("workPhone","Work");  
	ComboBoxItem primaryPhoneItem = new ComboBoxItem("primaryPhone","Primary phone");

	SelectItem countryItem = new SelectItem("country","Country");  
	TextItem cityItem = new TextItem("city","City");  
	TextItem addressLine1Item = new TextItem("addressLine1","AddressLine1");  
	TextItem addressLine2Item = new TextItem("addressLine2","AddressLine2");  
	TextItem postCodeItem = new TextItem("postCode","Post code");  

	
	
	
	
	
	ComboBoxItem genderItem = new ComboBoxItem("gender","Gender");
	ComboBoxItem titleItem = new ComboBoxItem("title","Title");
	ComboBoxItem occupationItem = new ComboBoxItem("occupation","Occupation");
	
	DateItem dateItem = new DateItem("birthDate","Birthday");  
	DateItem annivarseryItem = new DateItem("annivarsaryDate","Annivarsery");  
	

	TextItem emailItem = new TextItem("email","E-mail");  

	
	CheckboxItem doNotMailItem = new CheckboxItem("doNotMail","Do not mail");
	CheckboxItem doNotCallItem = new CheckboxItem("doNotCall","Do not call");
	CheckboxItem doNotSendSMSItem = new CheckboxItem("doNotSendSMS","Do not send sms");
	
	
	private void createGeneralForm(){
		SectionItem section = new SectionItem("general", "General");
		section.setSectionExpanded(true);
		section.setCanCollapse(false);
		section.setDefaultValue("General");
		section.setItemIds("id","firstName","lastName");
		firstNameItem.setRequired(true);
		lastNameItem.setRequired(true);
		generalForm.setColWidths(130,180);
		generalForm.setWidth(310);
		generalForm.setHeight100();
		generalForm.setItems(section,idItem,firstNameItem,lastNameItem);
		//generalForm.setItems(section);
		
	}  
	private void createPhoneForm(){
		SectionItem section = new SectionItem("phone", "Phone");
		section.setDefaultValue("Phone");
		section.setCanCollapse(false);
		section.setItemIds("homePhone","mobilePhone","workPhone","primaryPhone");
		phoneForm.setColWidths(130,180);
		phoneForm.setWidth(310);
		
		phoneForm.setHeight100();
		primaryPhoneItem.setType("comboBox");  
		primaryPhoneItem.setValueMap("Home phone", "Mobile phone", "Work home");
		
		phoneForm.setItems(section,homePhoneItem,mobilePhoneItem,workPhoneItem,primaryPhoneItem);
		
	}  

	private void createAddressForm(){
		SectionItem section = new SectionItem("address", "Address");
		section.setDefaultValue("Address");
		section.setCanCollapse(false);
		section.setTextAlign(Alignment.RIGHT);
		addressForm.setWidth("45%");
		addressForm.setHeight100();
		LinkedHashMap<String, String> valueMap = new LinkedHashMap<String, String>();  
		valueMap.put("poland", "Poland");
		valueMap.put("germany", "Germany");
		valueMap.put("czech", "Czech Rep.");
		valueMap.put("russia", "Russia");
		countryItem.setValueMap(valueMap);  
		countryItem.setImageURLPrefix("images/");
		countryItem.setImageURLSuffix(".png");
		
		
		
		LinkedHashMap<String, String> iconMap = new LinkedHashMap<String, String>();  
		valueMap.put("poland", "poland");
		valueMap.put("germany", "germany");
		valueMap.put("czech", "czech");
		valueMap.put("russia", "russia");
		
		countryItem.setValueIcons(iconMap);  
		
		
		addressForm.setColWidths(130,180);
		addressForm.setWidth(310);
		section.setItemIds("street","homeNumber","city","postCode","country");
		addressForm.setItems(section,addressLine1Item,addressLine2Item,cityItem,postCodeItem,countryItem);

	}
	
	private void createMiscellaneousForm(){
		SectionItem section = new SectionItem("miscellaneous", "Miscellaneous");
		section.setDefaultValue("Miscellaneous");
		section.setCanCollapse(false);

		miscellaneousForm.setWidth("45%");
		miscellaneousForm.setHeight100();
		
		dateItem.setDateFormatter(DateDisplayFormat.TOEUROPEANSHORTDATE);
		annivarseryItem.setDateFormatter(DateDisplayFormat.TOEUROPEANSHORTDATE);
		
		genderItem.setValueMap("Male","Female");
		titleItem.setValueMap("Mr.","Mrs.","Pan","Pani");
		occupationItem.setValueMap("Zlodziej","Oszust","Glupek","Jozek");
		annivarseryItem.setUseTextField(true);
		annivarseryItem.setAlign(Alignment.LEFT);
		section.setItemIds("gender","title","occupation","birthDate","annivarsaryDate");
		miscellaneousForm.setItems(section,genderItem, titleItem,occupationItem,dateItem,annivarseryItem);
		miscellaneousForm.setColWidths(130,180);
		miscellaneousForm.setWidth(310);

	}  
	
	private void createReferenceForm(){
		SectionItem section = new SectionItem("reference", "Reference");
		section.setDefaultValue("Reference");
		section.setCanCollapse(false);

		referenseForm.setWidth("45%");
		referenseForm.setHeight100();
		section.setItemIds("email");
		referenseForm.setItems(section,emailItem);
		referenseForm.setColWidths(130,180);
		referenseForm.setWidth(310);
		
	}
	  
	private void createMailingForm(){
		SectionItem section = new SectionItem("mailling", "Mailling");
		section.setDefaultValue("Reference");
		section.setCanCollapse(false);

		mailingForm.setWidth("45%");
		mailingForm.setHeight100();
		doNotCallItem.setTitleOrientation(TitleOrientation.LEFT);
		doNotMailItem.setTitleOrientation(TitleOrientation.LEFT);
		doNotSendSMSItem.setTitleOrientation(TitleOrientation.LEFT);
		doNotCallItem.setWidth(100);
		doNotMailItem.setWidth(100);
		doNotSendSMSItem.setWidth(100);
		//doNotCallItem.setHint("<nobr> This client does not want us to call him/her</nobr>");
		//doNotMailItem.setHint("<nobr>This client does not want to recive emails</nobr>");
		//doNotSendSMSItem.setHint("<nobr>This client does not to recive sms</nobr>");
		mailingForm.setItems(section,doNotCallItem,doNotMailItem,doNotSendSMSItem);
		mailingForm.setColWidths(130,180);
		mailingForm.setWidth(310);

	}  

	TabSet tabSetPanel = new TabSet();  
	Tab tabContact = new Tab("Contact information", "User-Administrator-Blue-icon.png");
	
	
	public AddClientWindow() {
		instance = this;
		init();
	}
	
	
	private ListGridRecord[] getAvailabeTitles(){
		ListGridRecord[] titles = new ListGridRecord[3];
		return titles;
	}

	private ClientDTO createClientDTOFromFormFileds(){
		ClientDTO clientDTO = new ClientDTO();
		return clientDTO;
		
	}
	
	private void init(){
		setWidth(700);  
		setHeight(550);  
		setTitle("Add client");  
		setShowMinimizeButton(false);
		setShowCloseButton(true);
		setIsModal(true);  
		setShowModalMask(true);  
		centerInPage();

		cancelButton.setWidth(100);
		cancelButton.setIcon("Cancel-2-icon.png");
		cancelButton.setIconOrientation("left");
		addButton.setIcon("accept-icon.png");  
		addButton.setIconOrientation("right");  
		addButton.setWidth(100);

		addButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				addNewClient();
			}
		});
		
		cancelButton.addClickHandler(new ClickHandler() {
			
			public void onClick(ClickEvent event) {
				AddClientWindow.instance.hide();
				AddClientWindow.instance.destroy();
				AddClientWindow.instance = null;
			}
		});
		
		tabSetPanel.setTabBarPosition(Side.TOP);  
		tabSetPanel.setTabBarAlign(Side.LEFT);
		tabSetPanel.setWidth100();  
		tabSetPanel.setHeight100();
		tabSetPanel.addTab(tabContact);
		
		createGeneralForm();
		createPhoneForm();
		createAddressForm();
		createMiscellaneousForm();
		createReferenceForm();
		createMailingForm();
		
		
		// tabContact
		HStack hStackA = new HStack();
		hStackA.setMembersMargin(20);
		hStackA.setWidth100();
		hStackA.setAlign(Alignment.CENTER);

	
		Img img = new Img("MailBox-icon.png", 48, 48);
		img.setLeft(20);
		img.setTop(40);
		hStackA.addChild(img);
		img = new Img("Network-Web-icon.png", 48, 48);
		img.setLeft(350);
		img.setTop(40);
		hStackA.addChild(img);
		hStackA.addMember(generalForm);
		hStackA.addMember(phoneForm);
		
		
		HStack hStackB = new HStack();
		hStackB.setMembersMargin(20);
		hStackB.setWidth100();
		hStackB.setAlign(Alignment.CENTER);

		img = new Img("MailBox-icon.png", 48, 48);
		img.setLeft(20);
		img.setTop(40);
		hStackB.addChild(img);
		img = new Img("Network-Web-icon.png", 48, 48);
		img.setLeft(350);
		img.setTop(40);
		hStackB.addChild(img);

		hStackB.addMember(addressForm);
		hStackB.addMember(miscellaneousForm);

		HStack hStackC = new HStack();
		hStackC.setMembersMargin(20);
		hStackC.setWidth100();
		hStackC.setAlign(Alignment.CENTER);
		img = new Img("MailBox-icon.png", 48, 48);
		img.setLeft(20);
		img.setTop(40);
		hStackC.addChild(img);
		img = new Img("Network-Web-icon.png", 48, 48);
		img.setLeft(350);
		img.setTop(40);
		hStackC.addChild(img);

		hStackC.addMember(referenseForm);
		hStackC.addMember(mailingForm);
		
		
		VStack vStack2 = new VStack();
		vStack2.setWidth100();
		vStack2.setMembersMargin(10);
		vStack2.addMember(hStackA);
		vStack2.addMember(hStackB);
		vStack2.addMember(hStackC);
		tabContact.setPane(vStack2);
		
		
		HStack hStack = new HStack();
		hStack.setHeight(30);
		hStack.setWidth100();
		hStack.addMember(cancelButton);
		hStack.addMember(addButton);
		hStack.setMembersMargin(20);
		hStack.setLeft(-40);
		hStack.setAlign(Alignment.RIGHT);

		
		HStack hStack2 = new HStack();
		hStack2.setWidth100();
		hStack2.setHeight(470);
		hStack2.setAlign(Alignment.CENTER);
		hStack2.addMember(tabSetPanel);


		VStack vStack = new VStack();
		vStack.setMembersMargin(20);

		vStack.addMember(hStack2);
		vStack.addMember(hStack);
		addItem(vStack);
		
		show();
	}	
	
	
	private ListGridRecord createClientDTOListGridRecord(ClientDTO clientDTO){
		ListGridRecord rec = new ListGridRecord();
		
		rec.setAttribute("id", clientDTO.getId());
		rec.setAttribute("email", clientDTO.getEmail());
		rec.setAttribute("firstName", clientDTO.getFirstName());
		rec.setAttribute("lastName", clientDTO.getLastName());
		rec.setAttribute("birthDate", clientDTO.getBirthDate());
		rec.setAttribute("anniversary", clientDTO.getAnnivarsery() );

		
		
		rec.setAttribute("mobilePhone", clientDTO.getMobilePhone());
		rec.setAttribute("workPhone", clientDTO.getWorkPhone());
		rec.setAttribute("homePhone", clientDTO.getHomePhone());
		rec.setAttribute("country", clientDTO.getCountry());
		rec.setAttribute("city", clientDTO.getCity());
		rec.setAttribute("addressLine1", clientDTO.getAddressLine1());
		rec.setAttribute("addressLine2", clientDTO.getAddressLine2());
		rec.setAttribute("postCode", clientDTO.getPostCode());
		rec.setAttribute("gender", clientDTO.getGender());
		rec.setAttribute("title", clientDTO.getTitle());
		rec.setAttribute("occupation", clientDTO.getOccupation());
		
		return rec;
	}
	
	
	private void addNewClient(){
		if (generalForm.validate() == false) return;  
		if (phoneForm.validate() == false) return;  
		if (addressForm.validate() == false) return;  
		if (miscellaneousForm.validate() == false) return;  
		if (referenseForm.validate() == false) return;  
		if (mailingForm.validate() == false) return;  
		ClientDTO clientDTO = new ClientDTO();
		
		clientDTO.setFirstName(generalForm.getValueAsString("firstName"));
		clientDTO.setLastName(generalForm.getValueAsString("lastName"));
		clientDTO.setHomePhone(phoneForm.getValueAsString("homePhone"));
		clientDTO.setMobilePhone(phoneForm.getValueAsString("mobilePhone"));
		clientDTO.setWorkPhone(phoneForm.getValueAsString("workPhone"));

		clientDTO.setPrimaryPhoneNumber(phoneForm.getValueAsString("primaryPhone"));
		
		clientDTO.setAddressLine1(addressForm.getValueAsString("addressLine1"));
		clientDTO.setAddressLine2(addressForm.getValueAsString("addressLine2"));
		clientDTO.setCity(addressForm.getValueAsString("city"));
		clientDTO.setPostCode(addressForm.getValueAsString("postCode"));
		clientDTO.setCountry(addressForm.getValueAsString("country"));
		clientDTO.setGender(miscellaneousForm.getValueAsString("gender"));
		clientDTO.setTitle(miscellaneousForm.getValueAsString("title"));
		clientDTO.setOccupation(miscellaneousForm.getValueAsString("occupation"));
		
		clientDTO.setBirthDate((Date)dateItem.getValue());
		clientDTO.setAnnivarsery((Date) annivarseryItem.getValue());
		
		clientDTO.setEmail(referenseForm.getValueAsString("email"));
		clientDTO.setDoNotCall( new Boolean(referenseForm.getValueAsString("doNotCall")));
		clientDTO.setDoNotMail( new Boolean(referenseForm.getValueAsString("doNotMail")));
		clientDTO.setDoNotSendSMS( new Boolean(referenseForm.getValueAsString("doNotSendSMS")));

		BeautySenseGWT.service.addClient(clientDTO, new AsyncCallback<ClientDTO>() {
			public void onSuccess(ClientDTO result) {
				ClientListPanel.instance.clientGrid.addData(createClientDTOListGridRecord(result));
				AddClientWindow.instance.hide();
				AddClientWindow.instance.destroy();
				AddClientWindow.instance = null;
			}
			
			public void onFailure(Throwable caught) {
			}
		});
	};
	
};
//--------------------------------------------------------------------------------------------------------------------------
class EditClientWindow extends Window{
	IButton cancelButton;
	IButton addButton;
	
	public EditClientWindow() {
		init();
	}
	
	private void init(){
		
	}
}